package org.example.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.mapper.OrderNumberMapper;
import org.example.model.entity.OrderNumber;
import org.example.service.OrderNumberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class OrderNumberServiceImpl extends ServiceImpl<OrderNumberMapper, OrderNumber> implements OrderNumberService {

    @Autowired
    private OrderNumberMapper orderNumberMapper;

    @Override
    public String generateOrderNumber(String id) {
        System.out.println("id = " + id);
        OrderNumber orderNumber = orderNumberMapper.selectById(id);
        if (orderNumber == null) {
            return "指定的单号规则不存在";
        }
        System.out.println("orderNumber = " + orderNumber);
        String encodingFormat = orderNumber.getEncodingFormat();
        String countMethod = orderNumber.getCountMethod();
        int currentCount = orderNumber.getCurrentCount();
        int initialValue = orderNumber.getInitialValue();

        // 生成日期部分
        String datePart = new SimpleDateFormat("yyMMdd").format(new Date());

        // 计算新的计数值
        int newCount = calculateNewCount(countMethod, currentCount, initialValue);

        // 生成数字部分
        String numberPart = generateNumberPart(newCount, encodingFormat);

        // 组合最终单号
        String finalOrderNumber = encodingFormat
                .replaceAll("&YYMMDD&", datePart)
                .replaceAll("@\\d+D", numberPart);

        // 更新当前计数
        orderNumber.setCurrentCount(newCount);
        orderNumberMapper.updateById(orderNumber);

        return finalOrderNumber;
    }

    private int calculateNewCount(String countMethod, int currentCount, int initialValue) {
        int newCount;
        switch (countMethod) {
            case "daily":
            case "monthly":
            case "yearly":
            case "continuous":
                newCount = currentCount + 1;
                break;
            default:
                newCount = currentCount;
                break;
        }
        return newCount;
    }

    private String generateNumberPart(int count, String encodingFormat) {
        String numberFormat = encodingFormat.replaceAll(".*@([0-9]+)D.*", "$1");
        int digits = Integer.parseInt(numberFormat);
        return String.format("%0" + digits + "d", count);
    }
}
